package com.kika.obwiki.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置类
 * 自定义异步线程池配置
 */
@Configuration
@EnableAsync
public class AsyncConfig {

  private static final Logger LOG = LoggerFactory.getLogger(AsyncConfig.class);

  /**
   * 自定义异步线程池
   * 
   * @return 异步执行器
   */
  @Bean("asyncExecutor")
  public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

    // 核心线程数
    executor.setCorePoolSize(5);
    // 最大线程数
    executor.setMaxPoolSize(20);
    // 队列容量
    executor.setQueueCapacity(100);
    // 线程名前缀
    executor.setThreadNamePrefix("Async-");
    // 线程空闲时间
    executor.setKeepAliveSeconds(60);
    // 拒绝策略：由调用线程处理
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    // 等待所有任务结束后再关闭线程池
    executor.setWaitForTasksToCompleteOnShutdown(true);
    // 等待时间
    executor.setAwaitTerminationSeconds(60);

    // 初始化
    executor.initialize();

    LOG.info("异步线程池配置完成：核心线程数={}, 最大线程数={}, 队列容量={}",
        executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity());

    return executor;
  }
}